/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package client;


import general.AgentType;
import general.Commands;
import general.Request;
import general.RequestBuilder;
import general.UDPConnection;
import general.UDPMessage;
import general.UDPTestConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;


/**
 *
 * @author foliveira
 */
public final class JFormUDPOrgao extends javax.swing.JFrame {

   
        
    /**
     * Creates new form JFormUDPOrgao
     */
    public JFormUDPOrgao() {
        
        
        initComponents();
        
        // iniciando minhas estruturas
        listLB = new ArrayList<>();
        connection = new UDPConnection();
        message = new UDPMessage(connection);
        
        displayOutput("Iniciando o Orgão.\n");                
        
        // Escutando as mensagens
        Runnable r = new Runnable() {

            @Override
            public void run() {
                whaitForMessage();
            }
                        
        };
        
        new Thread(r).start();
        
                
    }

    private void whaitForMessage() {
        
        Request response;
        String command=null;
        
        while (true) {

            try {

                request = new RequestBuilder(message.receive());
                response = request.getRequest();
                command = response.getCommand();
                
                
                if (command.contains("DATASERVICE")) {
                    displayOutput("recebeu " + response.toString());
                } 



            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }

    }
    
    public void getLoadBalanceEnable() {

        jComboBox1.removeAllItems();
        
        List<String> list = new ArrayList<>();

        list.add("localhost:9090");
        list.add("localhost:9091");
        list.add("localhost:9092");
        list.add("localhost:9093");
        list.add("localhost:9094");
        list.add("localhost:9095");

        displayOutput("Procurando LoadBalance ativos.\n");                
        
        for (Iterator<String> it = list.iterator(); it.hasNext();) {
            String host = it.next();

             displayOutput(String.format("Verificando o status do loadBalance %s.\n",host));                

             
            tConnection = new UDPTestConnection(host);

            if (tConnection.connected()) {
                displayOutput(String.format("O loadBalance %s esta ativo.\n",host));                
                listLB.add(host);
                jComboBox1.addItem(host);
            }else{
                displayOutput(String.format("O loadBalance %s não esta ativo.\n",host));                
            }


        }

    }
    
     private String[] getDataServerAvaliable() {

        String[] dataServer= new String[2];
        
        // procura um datasever nos lb
        for (Iterator<String> it = listLB.iterator(); it.hasNext();) {

            String host = it.next();
            tConnection = new UDPTestConnection(host);

            displayOutput(String.format("Solicitando um DataServer ao LoadBalance %s.\n", host));
            
            if (tConnection.connected()) {

                displayOutput(String.format("O loaadBalance %s respondeu.\n", host));  
                
                
                String text = ("ORGAO:WHO:DATA:USER:PASSWD:RETURN");
               
                try {

                    request = new RequestBuilder(text);
                    message = new UDPMessage(connection);
                    message.to(tConnection.getHost(), tConnection.getPort());
                    message.send(request.getRequest().toString());
                    displayOutput(String.format("Enviando a mensagem %s ao loadBalance %s respondeu.\n",Commands.WHO, host));       
                    
                   dataServer[0] = tConnection.getHost();
                   dataServer[1] = Integer.toString(tConnection.getPort());
 
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

                break;  // achando o primeiro abandona 

            }

            displayOutput(String.format("O LoadBalance %s não respondeu.\n", host));

        }

        return dataServer;
        
    }
    
    private void displayOutput(final String text){
        
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                jTextArea1.append(String.format("%s - %s",getCurrentDate(),text));
            }
        });
                
    }
     
    private String getCurrentDate(){
        Date d = new Date();
        SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        return df.format(d);
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jButton6 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jPanel3 = new javax.swing.JPanel();
        jComboBox1 = new javax.swing.JComboBox();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jButton7 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Orgão");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Commands"));

        jButton6.setText("Delete");
        jButton6.setEnabled(false);
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        jButton5.setText("Update");
        jButton5.setEnabled(false);

        jButton4.setText("Add");
        jButton4.setEnabled(false);
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton3.setText("Close");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton4)
                    .addComponent(jButton6)
                    .addComponent(jButton5)
                    .addComponent(jButton3))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Output message"));
        jPanel2.setToolTipText("");

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 178, Short.MAX_VALUE)
                .addContainerGap())
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Select server"));

        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        jButton1.setText("Search");
        jButton1.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Teste connection");
        jButton2.setEnabled(false);

        jLabel1.setText("Host");

        jButton7.setText("Edit");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(2, 2, 2)
                .addComponent(jComboBox1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addGap(18, 18, 18)
                .addComponent(jButton2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton7)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap(14, Short.MAX_VALUE)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jLabel1)
                    .addComponent(jButton7))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton6ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        
        // desabilita os botões
        enabledDisabled(false);
        
        jButton1.setEnabled(false);
        
        Runnable runnable = new  Runnable() {

            @Override
            public void run() {
                getLoadBalanceEnable();
                jButton1.setEnabled(true);
                
            }
            
        };
                
        new Thread(runnable).start();
        
    }//GEN-LAST:event_jButton1ActionPerformed

    private void enabledDisabled(boolean sender){
        
        jButton2.setEnabled(sender);
        jButton4.setEnabled(sender);
        jButton5.setEnabled(sender);
        jButton6.setEnabled(sender);
        
    }
    
    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed

       
        
        String[] dataServer;
        
               
        dataServer = getDataServerAvaliable();
        
        if (dataServer !=null){
            
            displayOutput(String.format("O orgao %s requisitando %s ao DataServer %s:%s.\n","g1",
                    Commands.ADD,dataServer[0],dataServer[1]));     
            
            
            
            try {
                
                String text = ("ORGAO:ADD:DATA:USER:PASSWD:RETURN");
                request = new RequestBuilder(text);
                message.to(dataServer[0], Integer.parseInt(dataServer[1]));
                message.send(request.getRequest().toString());
                
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            
        }else{
            displayOutput("Nenhum DataServer pode atender a requisiçaõ.\n");
        }
        
              
        
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        System.exit(0);
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        if (jComboBox1.getSelectedIndex()>-1)
            enabledDisabled(true);
        else
            enabledDisabled(false);
    }//GEN-LAST:event_jComboBox1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {                
                new JFormUDPOrgao().setVisible(true);               
            }
        });
        
        
    }
    
    
    private String name;
    private List<String> listLB;
    private Map<String, Double> mapEmployee;
    private UDPTestConnection tConnection;
    private UDPConnection connection;
    private UDPMessage message;
    private RequestBuilder request;
        
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JButton jButton7;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    // End of variables declaration//GEN-END:variables
}

